import React, { createContext, ReactElement } from 'react';
import { clone } from 'ramda';

import { State, Action, Context } from './types';
import actions from './actions';
import Provider from '../../components/Provider';
import { DOWNLOAD_MANAGE_TYPE } from './constant';
import { emptySortedDownloadVideoTasks } from '../../util/videoDownload/videoDownloadStore';

export const initialState: State = {
  type: DOWNLOAD_MANAGE_TYPE.All,
  isEdit: false,
  downloadingList: [],
  finishedList: [],
  selectedPIds: [],
  selectedAllDownloading: false,
  capacity: {
    freeCapacity: '',
    totalCapacity: ''
  },
  currentDownload: clone(emptySortedDownloadVideoTasks),
  netSpeed: 0
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_PAGE_TYPE': {
      return {
        ...state,
        type: action.value
      };
    }
    case 'SET_EDIT_STATUS': {
      if (action.value === false) {
        return {
          ...state,
          isEdit: action.value,
          selectedPIds: [],
          selectedAllDownloading: false
        };
      }
      return {
        ...state,
        isEdit: action.value
      };
    }
    case 'SET_DOWNLOADING_LIST': {
      return {
        ...state,
        downloadingList: action.value
      };
    }
    case 'SET_FINISHED_LIST': {
      return {
        ...state,
        finishedList: action.value
      };
    }
    case 'SET_SELECTED_PIDS': {
      return {
        ...state,
        selectedPIds: action.value
      };
    }
    case 'SET_CAPACITY': {
      return {
        ...state,
        capacity: action.value
      };
    }
    case 'SET_CURRENT_DOWNLOAD': {
      return {
        ...state,
        currentDownload: action.value
      };
    }
    case 'SET_NET_SPEED': {
      return {
        ...state,
        netSpeed: action.value
      };
    }
    case 'SET_SELECTED_ALL_DOWNLOADING': {
      return {
        ...state,
        selectedAllDownloading: action.value
      };
    }
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      {...props}
    />
  );
};
